package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioBean;
import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import jakarta.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties properties;
    @Autowired
    private MinioBean minioBean;

    @Override
    public String upload(MultipartFile file) {
        try {
            /*判断properties.getBucketName桶是否存在*/
            boolean b = minioBean.minioClient()
                    .bucketExists(BucketExistsArgs
                            .builder()
                            .bucket(properties.getBucketName())
                            .build());
            if (!b) {
                /*创建桶*/
                minioBean.minioClient()
                        .makeBucket(MakeBucketArgs.builder()
                                .bucket(properties.getBucketName())
                                .build());
                /*设置桶资源的访问权限*/
                minioBean.minioClient()
                        .setBucketPolicy(SetBucketPolicyArgs.builder()
                                .bucket(properties.getBucketName())
                                .config(BucketConfig())
                                .build());
            }

            String fileName =
                    /*时间*/
                    new SimpleDateFormat("yyyy:MM:dd").format(new Date()) +
                            /*UUid*/
                            UUID.randomUUID() + "-" +
                            /*原文件名*/
                            file.getOriginalFilename();

            /*以输入流（InputStream）的方式进行上传文件*/
            minioBean.minioClient().putObject(PutObjectArgs.builder()
                            .bucket(properties.getBucketName())
                            /*改变响应头中的contentType，否则有可能会在访问文件时直接下载*/
                            .contentType(file.getContentType())
                            /**
                             * file.getInputStream()：原文件的输入流
                             * file.getSize()：源文件大小
                             * partSize：切片大小设置，（-1：当文件大小确定时，输入-1自动配置合适的partSize）
                             */
                            .stream(file.getInputStream(), file.getSize(), -1)
                            /*文件名*/
                            .object(fileName)
                            .build());
            /*文件的minio地址*/
            String fileUrl = String.join("/", properties.getEndpoint(), properties.getBucketName(), fileName);
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 全部人可读，但不可写
     * @return
     */
    public String BucketConfig() {
        String config = """
                {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Effect": "Allow",
                        "Principal": "*",
                        "Action": "s3:GetObject",
                        "Resource": "arn:aws:s3:::%s/*"
                    }]
                }
                """.formatted(properties.getBucketName());
        return config;
    }
}
